package at.playbox.server.endpoints;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import at.playbox.server.businesslogic.AuthenticationService;
import at.playbox.server.businesslogic.ShopService;

public class DownloadSong extends HttpServlet
{
	private static final long serialVersionUID = 8790766092941539839L;

	static final int BUFFER_SIZE = 16384;

	public String reqId;

	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		try
		{
			AuthenticationService authService = new AuthenticationService();
			Map<String, String> parameters = req.getParameterMap();
			if (parameters.containsKey("id"))
			{
				if (authService.isAuthenticated(req))
				{
					reqId = req.getParameter("id");
					int id = Integer.parseInt(reqId);
					ShopService service = new ShopService();

					System.out.println("vorher");
					System.out.println(authService.getUsername());
					System.out.println(id);
					File file = service.downloadSong(id, authService.getUsername());
					if (file != null)
					{
						prepareResponseFor(res, file);
						streamFileTo(res, file);
					}
				}
				else
				{
					throw new RuntimeException("authentication is needed");
				}

			}
		}
		catch (Exception e)
		{
			PrintWriter out = res.getWriter();
			out.println(e);
			out.close();
		}
	}

	private void streamFileTo(HttpServletResponse response, File file) throws IOException, FileNotFoundException
	{
		OutputStream os = response.getOutputStream();
		FileInputStream fis = new FileInputStream(file);
		byte[] buffer = new byte[BUFFER_SIZE];
		int bytesRead = 0;
		while ((bytesRead = fis.read(buffer)) > 0)
		{
			os.write(buffer, 0, bytesRead);
		}
		os.flush();
		fis.close();
	}

	private void prepareResponseFor(HttpServletResponse response, File file)
	{
		StringBuilder type = new StringBuilder("attachment; filename=");
		type.append(file.getName());
		response.setContentLength((int) file.length());
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", type.toString());
	}

}